package com.songyang.blog.shiro;

import cn.hutool.json.JSONUtil;
import com.songyang.blog.common.lang.Result;
import com.songyang.blog.entity.User;
import com.songyang.blog.util.RedisUtil;
import com.songyang.blog.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.beans.factory.annotation.Autowired;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


public class AuthFilter extends UserFilter {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    ShiroUtils shiroUtils;


    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        User principal = (User) SecurityUtils.getSubject().getPrincipal();//获取现在登录的用户
        if (principal != null) {//如果获取到了说明已经有人登录了
            String redisTime = (String) redisUtil.get(principal.getEmail());//这个是刚才浏览器往Redis写入的数据,这个是用户最新的登录时间
            //这个是当前这个用户的登录时间
            String SessionTime = (String) ((HttpServletRequest) request).getSession().getAttribute("time" + principal.getEmail());
            // System.out.println("s："+SessionTime+"v："+redisTime+"time" + principal.getEmail());
            if (SessionTime != null && !SessionTime.equals(redisTime)) {//发现不一样，说明最新时间已经被更改过了注销之前的用户
                shiroUtils.logout();
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // ajax 弹窗显示未登录
        String header = httpServletRequest.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(header)) {
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            if (!authenticated) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.fail("请先登录!")));
            }
        } else {
            // web 重定向到登录页面
            super.redirectToLogin(request, response);
        }
    }

}
